import time
import pyvisa as visa
import logging

class power(object):
    def __init__(self,source='COM4',baudrate=9600):
        # visa_ref = visa.ResourceManager('@py')
        visa_ref = visa.ResourceManager()
        logging.info(visa_ref.list_resources())
        self.res=visa_ref.open_resource(source)

        logging.info(self.res.query("*IDN?"))
        CLS = self.res.write('*RST;*CLS')
        SYSTem_ERRor = self.res.query('SYSTem:ERRor?')  # 读取电源的错误代码及错误讯息。
        TST = self.res.query('*TST?')  # 自检，成功为0，失败则为1.
        self.Enable(False)
        logging.info('CLS'+'******'+SYSTem_ERRor+'******'+TST)

    def config(self,v_Protect = 20,c_Protect = 3):
        self.res.write(':SYSTem:REMote')  # 远程控制.
        self.res.write(':SYSTem:BEEPer 0')   # 关闭或打开蜂鸣器 0关闭
        self.res.write(':VOLT:PROT {0}'.format(v_Protect))  # 过压过流保护
        self.res.write(':CURR:PROT {0}'.format(c_Protect))  # 过压过流保护
        self.set_vltage(12)
        self.set_current(3)
        logging.info('set :VOLTage 12V;:PROTect {0};:CURRent 3A;:PROTect {1}'.format(v_Protect,c_Protect))

    def Enable(self, output):
        self.res.write('OUTP {0}'.format('1' if output else '0'))   # 关闭或打开电源 0关闭
        logging.info('Enable OUTP {0}'.format('ON ' if output else 'OFF'))

    def Read_Measure(self):
        VOLTage = 0
        CURRent = 0
        VOLTage = float(self.res.query('MEAsure:VOLTage?'))
        CURRent = float(self.res.query('MEAsure:CURRent?'))
        logging.info('VOLTage={0},CURRent = {1}'.format(VOLTage,CURRent))
        return VOLTage, CURRent
    
    def set_vltage(self,value):
        logging.info('Set VOLTage to {0}'.format(value))
        return self.res.write('VOLTage {0}'.format(value))
    
    def set_current(self,value):
        logging.info('Set CURRent to {0}'.format(value))
        return self.res.write('CURRent {0}'.format(value))

    def action(self,data):
        print('action is {0}'.format(data))
        logging.info('action is {0}'.format(data))
        return self.res.query(data)

    def close(self):
        self.Enable(False)
        self.res.write(':SYSTem:LOCal')  # 远程控制.
        logging.info('Close the power supply')

# run main
if __name__ == "__main__":
     try:
        #  power = power(source='USB0::0x2EC7::0x6900::800062020757810055::INSTR',baudrate=9600)
         power = power(source='DCSource',baudrate=9600)
         power.config()
         power.Enable(True)
         v,i =power.Read_Measure()
         print(v,i)
         power.set_vltage(14)
         time.sleep(1)
         v,i =power.Read_Measure()
         
         power.close()

     except Exception as e:
         power.close()
         import sys
         import traceback
         print(traceback.print_exc())
         sys.exit(0)
         pass